package reflect;

import java.lang.reflect.Method;
import java.util.Scanner;

/**
 * 使用反射机制调用方法
 */
public class ReflectDemo4 {
    public static void main(String[] args) throws Exception {
        Person p = new Person();
        p.sayGoodBye();

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入类名:");
        String className = scanner.nextLine();
        System.out.println("请输入方法名:");
        String methodName = scanner.nextLine();
        //1加载类对象
//        Class cls = Class.forName("reflect.Person");
        Class cls = Class.forName(className);
        //2实例化
        Object obj = cls.newInstance();//使用默认构造器实例化对象  Person p = new Person();
        //3根据类对象获取要操作的方法对象 java.lang.reflect.Method
//        Method method = cls.getMethod("sayGoodBye");
        Method method = cls.getMethod(methodName);
        //4调用该方法
        method.invoke(obj);//p.sayGoodBye();
    }
}
